 import axios, { AxiosInstance } from "axios";
import eventBus from "../utils/event-bus.js";
import { ElMessage } from "element-plus";
const service: AxiosInstance = axios.create({
  baseURL: "http://8.134.82.99/go-api/v1/",
  timeout: 5000,
});

service.interceptors.request.use( 
  (config: any) => {
    config.headers!["Authorization"] =
      "bearer " + localStorage.getItem("token") || "";
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
service.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // token过期就跳转到登录页
    if (error.response && error.response.status === 401) {
      eventBus.emit("logout-event", {});
      ElMessage.error("登录失效，请重新登录");
      localStorage.removeItem("token");
    }
    return Promise.reject(error);
  }
);

export default service;